/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.booting.balancer4j;

/**
 * A {@link LoadBalancer} implementations which sends to all destinations
 * (rather like JMS Topics).
 * <p/>
 * The {@link Candidate} is more powerful as it offers
 * option to run in parallel and decide whether or not to stop on failure etc.
 */
public class TopicLoadBalancer extends LoadBalancerSupport {

    public boolean process(final Action exchange, final Callback callback) {
        Candidate[] processors = doGetCandidates();
        REACTIVE.schedule(new State(exchange, callback, processors)::run);
        return false;
    }

    protected class State {
        final Action action;
        final Callback callback;
        final Candidate[] processors;
        int index;

        public State(Action exchange, Callback callback, Candidate[] processors) {
            this.action = exchange;
            this.callback = callback;
            this.processors = processors;
        }

        public void run() {
            if (index < processors.length) {
                Candidate processor = processors[index++];
                processor.process(action, doneSync -> done(action));
            } else {
                callback.done(false);
            }
        }

        public void done(Action current) {
            if (current.getException() != null) {
                action.setException(current.getException());
                callback.done(false);
            } else {
                REACTIVE.schedule(this::run);
            }
        }
    }

}
